package com.test06.mail;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

/*
 * 这是使用javaMail来完成发送邮件的功能
 * 总结：
 *    1.发送邮件一共需要创建Properties、Authenticator、Session、MimeMessage对象
 *    2.抄送和收件人的区别，就在于指定的时候指定的用户类型不同（接收人是RecipientType.TO，抄送是RecipientType.CC）
 */
public class MailStart02 {
	public static void main(String[] args) {
	}

	public void sendMail(String loginName, String password, Address[] receives, Address[] copyTo, String subject,
			String content) throws Exception {
		// 设置连接配置信息
		final Properties properties = new Properties();
		properties.put("mail.user", "wangquannetwork@163.com");
		properties.put("mail.password", "xxxxxxxxx");
		properties.put("mail.smtp.host", "smtp.163.com");
		properties.put("mail.smtp.auth", "true");
		
		
		// 创建验证对象，抽象类，里面某个方法是空的，需要自己取重写用户名和密码验证信息
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(properties.getProperty("mail.user"),
						properties.getProperty("mail.password"));
			}
		};
		
		
		// 创建邮件session会话
		Session session = Session.getInstance(properties, authenticator);
		
		// 创建邮件内容对象
		MimeMessage mimeMessage = new MimeMessage(session);
		// 发送人
		mimeMessage.setSender(new InternetAddress(loginName));
		// 接收人
		mimeMessage.setRecipients(RecipientType.TO, receives);
		// 抄送
		mimeMessage.setRecipients(RecipientType.CC, copyTo);
		// 主题
		mimeMessage.setSubject(subject);
		// 内容
		mimeMessage.setContent(content, "text/html;charset=UTF-8");

		// 发送消息
		Transport.send(mimeMessage);
	}
}
